package com.qiantu.phone.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import androidx.annotation.Nullable;

import com.hjq.base.DensityUtils;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

/**
 * @ClassName RoundSeekBar
 * @Description TODO
 * @Author ShiJunqiang
 * @Date 2021/5/21 16:54
 * @Version 1.0
 */
public class RoundSeekBar extends View {
    /**
     * 圆环笔画的宽度
     */
    private float mStrokeWidth;
    /**
     * 着色器
     */
    private static final int LINE_COUNT = 19;
    private static final int LINE_START_DEGREES = 36;
    private static final int CALCULATE_START_DEGREES = 54;
    private static final int START_DEGREES = 126;
    private static final int TOTAL_DEGREES = 288;
    private static final int DEGREE_PER_LINE = TOTAL_DEGREES / (LINE_COUNT - 1) - 1;//每个刻度的间隔角度
    private static final int LINE_START_DEGREES_OFFSET = (LINE_COUNT - 1) / 2;
    private static final String UNIT_TEXT = "%";
    private final int MAX = 100;
    //默认设置50%亮度
    private int mProgress;
    private int defaultProgress = 100;
    private int shadow;
    private boolean offIsShowCenterDrawable;
    private Drawable centerOnDrawable;
    private Drawable centerOffDrawable;
    private RectF arcRectF;
    private RectF lineRectF;
    private int lineWidth;
    private int barRadius;
    private int barStrokeWidth;
    private LinearGradient mGradient;
    private Paint mPaint;
    private TextPaint mTextPaint;
    private int closeTextSize;
    private int percentageTextSize;
    private int unitAndLabelTextSize;
    private String closeText;
    private String labelText;
    private String unitText;
    private int percentage_unit_padding;
    private int percentage_label_padding;
    private boolean isOpen = false;
    //圆弧区域内down
    private boolean isInArcDown;
    //圆环区域内down
    private boolean isInRingDown;
    //开关范围
    private Rect switchRect;
    private int switchClickPadding;
    private boolean isSwitchDown;
    private double mLastDegrees = -1;
    private double mCurrentDegrees;
    //拖拽是否继续更改进度环
    private boolean dragFlag = true;
    private float mDownX;
    private float mDownY;
    //有没有move进圆弧内
    private boolean hasMoveInArc;
    //是否是设备动作
    private boolean isSetAction;
    private float centerRadius;
    private int deviceSolidBgColor;

    public RoundSeekBar(Context context) {
        this(context, null);
    }

    public RoundSeekBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RoundSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        shadow = DensityUtils.dip2px(getContext(), 20);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RoundSeekBar);
        mStrokeWidth = ta.getDimension(R.styleable.RoundSeekBar_stroke_width, DensityUtils.dip2px(getContext(), 20));
        offIsShowCenterDrawable = ta.getBoolean(R.styleable.RoundSeekBar_off_is_show_center_drawable, false);
        isSetAction = ta.getBoolean(R.styleable.RoundSeekBar_is_set_action, false);
        centerOnDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_devicecontrol_curtain_switch_3);
        centerOffDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_devicecontrol_curtain_switch_2);
        deviceSolidBgColor = AppApplication.getInstance().getThemeColor(R.attr.deviceSolidBgColor);
        ta.recycle();
        arcRectF = new RectF();
        lineRectF = new RectF();
        lineWidth = getResources().getDimensionPixelSize(R.dimen.dp_3);
        barRadius = getResources().getDimensionPixelSize(R.dimen.dp_14);
        barStrokeWidth = getResources().getDimensionPixelSize(R.dimen.dp_1);
        closeTextSize = getResources().getDimensionPixelSize(R.dimen.dp_20);
        percentageTextSize = getResources().getDimensionPixelSize(R.dimen.dp_32);
        unitAndLabelTextSize = getResources().getDimensionPixelSize(R.dimen.dp_12);
        percentage_unit_padding = getResources().getDimensionPixelSize(R.dimen.dp_5);
        percentage_label_padding = getResources().getDimensionPixelSize(R.dimen.dp_8);
        switchRect = new Rect();
        switchClickPadding = getResources().getDimensionPixelSize(R.dimen.dp_10);
        closeText = getResources().getString(R.string.switch_off);
        labelText = getResources().getString(R.string.brightness);
    }

    public void setSetAction(boolean setAction) {
        isSetAction = setAction;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int defaultValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
        int width = measureHandler(widthMeasureSpec, defaultValue);
        int height = measureHandler(heightMeasureSpec, defaultValue);
        setMeasuredDimension(Math.min(width, height), Math.min(width, height));
    }

    /**
     * 测量
     *
     * @param measureSpec
     * @param defaultSize
     * @return
     */
    private int measureHandler(int measureSpec, int defaultSize) {
        int result = defaultSize;
        int measureMode = MeasureSpec.getMode(measureSpec);
        int measureSize = MeasureSpec.getSize(measureSpec);
        if (measureMode == MeasureSpec.EXACTLY) {
            result = measureSize;
        } else if (measureMode == MeasureSpec.AT_MOST) {
            result = Math.min(defaultSize, measureSize);
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawArc(canvas);
    }

    private void drawArc(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();
        int centerX = width / 2;
        int centerY = height / 2;
        int radius = Math.min(centerX, centerY);
        centerRadius = radius - mStrokeWidth * 2;

        arcRectF.left = mStrokeWidth / 2 + mStrokeWidth;
        arcRectF.top = centerY - radius + mStrokeWidth / 2 + mStrokeWidth;
        arcRectF.right = width - mStrokeWidth / 2 - mStrokeWidth;
        arcRectF.bottom = centerY + radius - mStrokeWidth / 2 - mStrokeWidth;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor10));
        canvas.drawArc(arcRectF, START_DEGREES, TOTAL_DEGREES, false, mPaint);

        canvas.save();
        mPaint.setStyle(Paint.Style.FILL);
        lineRectF.left = centerX - lineWidth / 2;
        lineRectF.top = getHeight() - getResources().getDimensionPixelSize(R.dimen.dp_6) - lineWidth / 2;
        lineRectF.right = centerX + lineWidth / 2;
        lineRectF.bottom = getHeight() - lineWidth / 2;
        canvas.rotate(LINE_START_DEGREES + LINE_START_DEGREES_OFFSET, centerX, centerY);
//        for (int i = 0; i < LINE_COUNT; i++) {
//            canvas.drawRoundRect(lineRectF, lineWidth, lineWidth, mPaint);
//            canvas.rotate(DEGREE_PER_LINE, centerX, centerY);
//        }
        canvas.restore();

        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(deviceSolidBgColor);
        mPaint.setShadowLayer(shadow, 0, getResources().getDimensionPixelSize(R.dimen.dp_11), 0x3025334b);
        canvas.drawCircle(centerX, centerY, centerRadius, mPaint);
        mPaint.setShadowLayer(0, 0, 0, 0);

        int bottom = (int) (centerY + centerRadius - mStrokeWidth);
        mTextPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6));
        if (mProgress == 0 || !isOpen) {
            if(isOpen && isSetAction){//是设备动作并且未设置亮度
                //画白球
                int barCenterToCenter = (int) (radius - mStrokeWidth - mStrokeWidth / 2);
                int barCenterX = (int) (centerX - (Math.cos((-CALCULATE_START_DEGREES) * Math.PI / 180) * barCenterToCenter));
                int barCenterY = (int) (centerY - (Math.sin((-CALCULATE_START_DEGREES) * Math.PI / 180) * barCenterToCenter));
                mPaint.setColor(0xffffffff);
                canvas.drawCircle(barCenterX, barCenterY, barRadius, mPaint);
                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setStrokeWidth(barStrokeWidth);
                mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4));
                canvas.drawCircle(barCenterX, barCenterY, barRadius - barStrokeWidth / 2, mPaint);

                //画未设置文字
                mTextPaint.setTextSize(closeTextSize);
                mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
                String text = getResources().getString(R.string.not_set);
                float textWidth = mTextPaint.measureText(text);
                Paint.FontMetricsInt textFontMetricsInt = mTextPaint.getFontMetricsInt();
                int textHeight = textFontMetricsInt.descent - textFontMetricsInt.ascent;
                float textY = centerY + textHeight / 2 - textFontMetricsInt.descent;
                float percentageX = centerX - textWidth / 2;
                canvas.drawText(text, percentageX, textY, mTextPaint);

                mTextPaint.setTextSize(unitAndLabelTextSize);
                mTextPaint.setTypeface(Typeface.DEFAULT);
                float labelTextWidth = mTextPaint.measureText(labelText);
                Paint.FontMetricsInt fontMetricsInt = mTextPaint.getFontMetricsInt();
                int labelTextHeight = fontMetricsInt.descent - fontMetricsInt.ascent;
                float labelTextY = centerY + labelTextHeight / 2 - fontMetricsInt.descent - percentage_label_padding  - textHeight / 2;
                canvas.drawText(labelText, centerX - labelTextWidth / 2, labelTextY, mTextPaint);

                //画开关按钮
                if (centerOnDrawable != null) {
                    switchRect.left = radius - centerOnDrawable.getIntrinsicWidth() / 2;
                    switchRect.top = bottom - centerOnDrawable.getIntrinsicHeight();
                    switchRect.right = radius + centerOnDrawable.getIntrinsicWidth() / 2;
                    switchRect.bottom = bottom;
                    centerOnDrawable.setBounds(switchRect);
                    centerOnDrawable.draw(canvas);
                }
            }else{//关闭状态
                //画关闭文字
                mTextPaint.setTextSize(closeTextSize);
                mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
                float textWidth = mTextPaint.measureText(closeText);
                Paint.FontMetricsInt fontMetricsInt = mTextPaint.getFontMetricsInt();
                int textHeight = fontMetricsInt.descent - fontMetricsInt.ascent;
                float textY = centerY + textHeight / 2 - fontMetricsInt.descent;
                float textX = centerX - textWidth / 2;
                canvas.drawText(closeText, textX, textY, mTextPaint);
                if (offIsShowCenterDrawable && centerOffDrawable != null) {
                    switchRect.left = radius - centerOffDrawable.getIntrinsicWidth() / 2;
                    switchRect.top = bottom - centerOffDrawable.getIntrinsicHeight();
                    switchRect.right = radius + centerOffDrawable.getIntrinsicWidth() / 2;
                    switchRect.bottom = bottom;
                    centerOffDrawable.setBounds(switchRect);
                    centerOffDrawable.draw(canvas);
                } else {
                    switchRect.left = (int) textX;
                    switchRect.top = centerY - textHeight / 2;
                    switchRect.right = (int) (textX + textWidth);
                    switchRect.bottom = centerY + textHeight / 2;
                }
            }
        } else {
            /*画进度*/
            float currentDegrees = mProgress / 100f * TOTAL_DEGREES;
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(mStrokeWidth);
            if (mGradient == null) {
                mGradient = new LinearGradient(getWidth(), 0, 0, getHeight(), 0xffFFDA7D, 0xffFFB347, Shader.TileMode.CLAMP);
            }
            mPaint.setShader(mGradient);
            canvas.drawArc(arcRectF, START_DEGREES, currentDegrees, false, mPaint);

            canvas.save();
            mPaint.setStyle(Paint.Style.FILL);
            lineRectF.left = centerX - lineWidth / 2;
            lineRectF.top = getHeight() - getResources().getDimensionPixelSize(R.dimen.dp_6) - lineWidth / 2;
            lineRectF.right = centerX + lineWidth / 2;
            lineRectF.bottom = getHeight() - lineWidth / 2;
            canvas.rotate(LINE_START_DEGREES + LINE_START_DEGREES_OFFSET, centerX, centerY);
            for (int i = 0; i < LINE_COUNT; i++) {
                if (LINE_START_DEGREES_OFFSET + DEGREE_PER_LINE * i > currentDegrees) {
                    break;
                }
                canvas.drawRoundRect(lineRectF, lineWidth, lineWidth, mPaint);
                canvas.rotate(DEGREE_PER_LINE, centerX, centerY);
            }
            canvas.restore();
            mPaint.setShader(null);
            /*画进度*/

            //画白球
            int barCenterToCenter = (int) (radius - mStrokeWidth - mStrokeWidth / 2);
            int barCenterX = (int) (centerX - (Math.cos((currentDegrees - CALCULATE_START_DEGREES) * Math.PI / 180) * barCenterToCenter));
            int barCenterY = (int) (centerY - (Math.sin((currentDegrees - CALCULATE_START_DEGREES) * Math.PI / 180) * barCenterToCenter));
            mPaint.setColor(0xffffffff);
            canvas.drawCircle(barCenterX, barCenterY, barRadius, mPaint);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(barStrokeWidth);
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4));
            canvas.drawCircle(barCenterX, barCenterY, barRadius - barStrokeWidth / 2, mPaint);

            unitText = UNIT_TEXT;
            String text = mProgress < 10 ? "0" + mProgress : "" + mProgress;
            mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
            mTextPaint.setTextSize(percentageTextSize);
            float maxTextWidth = mTextPaint.measureText("100");
            float percentageTextWidth = mTextPaint.measureText(text);

            Paint.FontMetricsInt percentageTexFontMetricsInt = mTextPaint.getFontMetricsInt();
            int percentageTextHeight = percentageTexFontMetricsInt.descent - percentageTexFontMetricsInt.ascent;
            float percentageTextY = centerY + percentageTextHeight / 2 - percentageTexFontMetricsInt.descent;

            mTextPaint.setTextSize(unitAndLabelTextSize);
            mTextPaint.setTypeface(Typeface.DEFAULT);
            float labelTextWidth = mTextPaint.measureText(labelText);
            float unitTextWidth = mTextPaint.measureText(unitText);
            Paint.FontMetricsInt fontMetricsInt = mTextPaint.getFontMetricsInt();
            int unitAndLabelTextHeight = fontMetricsInt.descent - fontMetricsInt.ascent;
            float labelTextY = centerY + unitAndLabelTextHeight / 2 - fontMetricsInt.descent - (percentage_label_padding + percentageTextHeight / 2);
            float unitTextY = centerY + unitAndLabelTextHeight / 2 - fontMetricsInt.descent + (percentageTextHeight - unitAndLabelTextHeight) / 4;
            canvas.drawText(labelText, centerX - labelTextWidth / 2, labelTextY, mTextPaint);

            float percentageX = centerX - (maxTextWidth + percentage_unit_padding + unitTextWidth) / 2;
            canvas.drawText(unitText, percentageX + maxTextWidth + percentage_unit_padding, unitTextY, mTextPaint);

            mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
            mTextPaint.setTextSize(percentageTextSize);
            canvas.drawText(text, percentageX + (maxTextWidth - percentageTextWidth), percentageTextY, mTextPaint);
            if (centerOnDrawable != null) {
                switchRect.left = radius - centerOnDrawable.getIntrinsicWidth() / 2;
                switchRect.top = bottom - centerOnDrawable.getIntrinsicHeight();
                switchRect.right = radius + centerOnDrawable.getIntrinsicWidth() / 2;
                switchRect.bottom = bottom;
                centerOnDrawable.setBounds(switchRect);
                centerOnDrawable.draw(canvas);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isEnabled()) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mDownX = event.getX();
                    mDownY = event.getY();
                    //按下时候进度一点一点的移动
//                    mLastDegrees = getTouchAngle(downX, downY);
                    if (isInRingArea(mDownX, mDownY)) {
                        isInRingDown = true;
                        isInArcDown = isInArcArea(mDownX, mDownY);
                    } else {
                        isInRingDown = false;
                        isInArcDown = false;
                        //开关点击范围
                        isSwitchDown = isInSwitchArea(mDownX, mDownY);
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    //down不在圆环里不触发滑动进度
                    if(!isInRingDown){
                        return true;
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                    float moveX = event.getX();
                    float moveY = event.getY();
                    double moveDegrees = getTouchAngle(moveX, moveY);
                    if(mLastDegrees == -1){
                        //第一次move,判断在不在圆弧里
                        if(isInArcArea(moveX, moveY)){
                            mCurrentDegrees = moveDegrees;
                            mLastDegrees = moveDegrees;
                            hasMoveInArc = true;
                        }else{
                            hasMoveInArc = false;
                            return true;
                        }
                    }else{
                        calculateDegrees(moveDegrees);
                    }
                    calculateProgress();
                    if (mOnChangeListener != null) {
                        mOnChangeListener.onProgressChanged(mProgress);
                    }
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    float upX = event.getX();
                    float upY = event.getY();
//                    float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(upX - mDownX), 2) + Math.pow(Math.abs(upY - mDownY), 2));
                    //down在圆环里
                    if(isInRingDown){
                        //点击圆弧内，就用up左边重新计算最后一次百分比，并回调
                        if (isInArcDown && isInArcArea(upX, upY) && dragFlag) {
                            mCurrentDegrees = getTouchAngle(upX, upY);
                            calculateProgress();
                            if (mOnChangeListener != null) {
                                playSoundEffect(SoundEffectConstants.CLICK);
                                mOnChangeListener.onStopTrackingTouch(mProgress);
                            }
                            invalidate();
                        }else{//up不在圆弧区域内，但是move到圆弧内过，就直接回调move最后一次百分比
                            if (hasMoveInArc && mOnChangeListener != null) {
                                playSoundEffect(SoundEffectConstants.CLICK);
                                mOnChangeListener.onStopTrackingTouch(mProgress);
                            }
                        }
                    }else{
                        //点击开关按钮
                        if (isSwitchDown && isInSwitchArea(upX, upY)) {
                            isOpen = !isOpen;
                            //如果打开，并且亮度是0，那么就设置默认亮度
//                            if(isOpen && mProgress == 0){
//                                mProgress = defaultProgress;
//                            }
                            invalidate();
                            if (mOnChangeListener != null) {
                                playSoundEffect(SoundEffectConstants.CLICK);
                                mOnChangeListener.onSwitch(isOpen);
                            }
                        }
                    }
                    isSwitchDown = false;
                    isInArcDown = false;
                    dragFlag = true;
                    hasMoveInArc = false;
                    mLastDegrees = -1;
                    getParent().requestDisallowInterceptTouchEvent(false);
                    break;
                case MotionEvent.ACTION_CANCEL:
                    isSwitchDown = false;
                    isInArcDown = false;
                    dragFlag = true;
                    hasMoveInArc = false;
                    mLastDegrees = -1;
                    getParent().requestDisallowInterceptTouchEvent(false);
                    break;
            }
        }
        return true;
    }

    private void calculateDegrees(double moveDegrees){
        Log.i("lzx", "moveDegrees:" + moveDegrees);
        double changeDegrees = 0;
        if(dragFlag){
            changeDegrees = moveDegrees - mLastDegrees;
            mCurrentDegrees += changeDegrees;
            //一次移动角度超过300，就是滑动到了结束和开始的边界（顺时针）
            if (mLastDegrees - moveDegrees > 300){
                dragFlag = false;
                mCurrentDegrees = TOTAL_DEGREES;
            }
            //一次移动角度超过300，就是滑动到了结束和开始的边界（逆时针）
            if (moveDegrees - mLastDegrees > 300){
                dragFlag = false;
                mCurrentDegrees = 0;
            }
        }else {
            //到达最大值后，上一次角度大于当前角度（即正在逆时针拖拽）
            if (mCurrentDegrees == TOTAL_DEGREES && (mLastDegrees - moveDegrees > 0)){
                double diff = TOTAL_DEGREES - moveDegrees;
                if(diff < 45 && diff > 0){
                    dragFlag = true;
                }
            }
            //到达最小值后，当前角度大于上一次角度（即正在顺时针拖拽）
            if (mCurrentDegrees == 0 && mLastDegrees - moveDegrees > 300){
                if(mLastDegrees - moveDegrees > 0){
                    dragFlag = true;
                }
            }
        }
        mLastDegrees = moveDegrees;
        Log.i("lzx", "mCurrentDegrees:" + mCurrentDegrees);
    }

    private boolean isInSwitchArea(float x, float y) {
//        //点击开关图标
//        return (switchRect.left - switchClickPadding <= x && x <= switchRect.right + switchClickPadding)
//                && (switchRect.top - switchClickPadding <= y && y <= switchRect.bottom + switchClickPadding);
        float centerX = getWidth() / 2;
        float centerY = getHeight() / 2;
        float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(x - centerX), 2) + Math.pow(Math.abs(y - centerY), 2));
        return clickDistance < centerRadius;
    }

    private boolean isInArcArea(float x, float y) {
        double currentDegrees = getTouchAngle(x, y);
        //角度限制放宽5，优化触控体验
        return isInRingArea(x, y) && currentDegrees <= TOTAL_DEGREES + 5 && (currentDegrees >= 0 || currentDegrees < 355);
    }

    private boolean isInRingArea(float x, float y) {
        float centerX = getWidth() / 2;
        float centerY = getHeight() / 2;
        float distance = (float) Math.sqrt(Math.pow(Math.abs(centerX - x), 2) + Math.pow(Math.abs(centerY - y), 2));
        //点坐标在圆内，并且大于白色圆球最外侧(圆环内可拖动)
        return distance <= centerX && distance >= centerX - (mStrokeWidth + mStrokeWidth + barRadius - mStrokeWidth / 2f);
    }

    private void calculateProgress() {
        mProgress = (int) (mCurrentDegrees / TOTAL_DEGREES * 100);
        if (mProgress > 100) {
            mProgress = 100;
        }
        if (mProgress < 0) {
            mProgress = 0;
        }
        if(mProgress > 0){
            isOpen = true;
        }else{
            isOpen = false;
        }
    }

    /**
     * 获取触摸坐标的夹角度数
     *
     * @param x
     * @param y
     * @return
     */
    private float getTouchAngle(float x, float y) {
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        //求触摸点弧形的夹角度数
        int angle = (int) (Math.atan2((centerY - y), (centerX - x)) * 180 / Math.PI + CALCULATE_START_DEGREES);
        while (angle < 0) {
            angle += 360;
        }
        return angle;
    }

    public void setProgress(int progress) {
        if (progress < 0) {
            progress = 0;
        } else if (progress > MAX) {
            progress = MAX;
        }
        this.mProgress = progress;
//        preProgress = mProgress;
        mCurrentDegrees = mProgress / 100f *  TOTAL_DEGREES;
        invalidate();
    }

    public void setOpenState(boolean openState) {
        if(isOpen == openState){
            return;
        }
//        if (openState) {
//            mProgress = preProgress;
//        } else {
//            preProgress = mProgress;
//            mProgress = 0;
//        }
//        mCurrentDegrees = mProgress / 100f *  TOTAL_DEGREES;
        isOpen = openState;
        invalidate();
    }

    public boolean isOpen() {
        return isOpen;
    }

    public int getProgress() {
        return mProgress;
    }

    private OnChangeListener mOnChangeListener;

    public void setOnChangeListener(OnChangeListener mOnChangeListener) {
        this.mOnChangeListener = mOnChangeListener;
    }

    public interface OnChangeListener {
        void onProgressChanged(int value);

        void onStopTrackingTouch(int value);

        void onSwitch(boolean isOpen);
    }

    /**
     * 显示进度动画效果，从from到to变化
     *
     * @param from
     * @param to
     * @param duration 动画时长
     * @param listener
     */
    public void showAnimation(int from, int to, int duration, Animator.AnimatorListener listener) {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(from, to);
        valueAnimator.setDuration(duration);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                setProgress((int) animation.getAnimatedValue());
            }
        });

        if (listener != null) {
            valueAnimator.removeAllUpdateListeners();
            valueAnimator.addListener(listener);
        }

        valueAnimator.start();
    }
}
